package com.mr.cai.main.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.mr.cai.main.R;
import com.mr.cai.main.utils.CommonCoreUtil;
import com.mr.cai.main.utils.MrCaiConstant;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by hai8108 on 16/2/10.
 */
public class HomePageFragment extends BaseFragment {
    private TextView nav_home;
    private HashMap<String, String> oldKeyMap = new HashMap<>();
    private HashMap<String, String> hasKeyMap = new HashMap<>();
    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mPublicLayout = CommonCoreUtil.createPage(getActivity(), R.layout
                .fragment_page_home_layout);
        nav_home = (TextView) mPublicLayout.findViewById(R.id.navi_home_txt);
        return mPublicLayout;
    }

    @Override
    public void onViewCreated (View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated (Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        readExcel("2014_no.xls");
    }

    public void readExcel (String fileName) {
        Observable.just(fileName)
                .subscribeOn(Schedulers.io())
                .map(new Func1<String, String>() {
                    @Override
                    public String call (String s) {
                        try {
                            /**
                             * 后续考虑问题,比如Excel里面的图片以及其他数据类型的读取
                             **/
                            InputStream is = null;//new FileInputStream("mnt/sdcard/test.xls");
                            is = getActivity().getAssets().open(s);
                            //Workbook book = Workbook.getWorkbook(new File("mnt/sdcard/test.xls"));
                            Workbook book = Workbook.getWorkbook(is);
                            int num = book.getNumberOfSheets();
                            // 获得第一个工作表对象
                            Sheet sheet = book.getSheet(0);
                            int Rows = sheet.getRows();
                            int Cols = sheet.getColumns();
                            StringBuilder sb = new StringBuilder();
                            sb.append("the name of sheet is " + sheet.getName() + "\n");
                            sb.append("total rows is " + Rows + "\n");
                            sb.append("total cols is " + Cols + "\n");
                            String tmpStr = null;
                            Cell contentCell = null;
                            String key = null;
                            String values = null;
                            Log.e("haitian", sb.toString());
                            for (int i = 2; i < Rows; ++i) {
                                key = sheet.getCell(1, i).getContents();
                                key += sheet.getCell(3, i).getContents();
                                key = key.replaceAll(" ","");
                                values = sheet.getCell(4, i).getContents();
                                Log.e("haitian", key + "----" + values);
                                if (!oldKeyMap.containsKey(key)) {
                                    oldKeyMap.put(key, values);
                                }
                            }
                            book.close();
                            return sb.toString();
                        } catch (Exception e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                }).subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
            @Override
            public void onCompleted () {
                updateExcel("2015.xls");
            }

            @Override
            public void onError (Throwable e) {

            }

            @Override
            public void onNext (String s) {
                Log.e("haitian", "s =" + s);
//                nav_home.setText(s);
            }
        });
    }

    /**
     * jxl暂时不提供修改已经存在的数据表,这里通过一个小办法来达到这个目的,不适合大型数据更新! 这里是通过覆盖原文件来更新的.
     *
     * @param filePath
     */
    public void updateExcel(String filePath) {
        Observable.just(filePath)
                .subscribeOn(Schedulers.io())
                .map(new Func1<String, String>() {
                    @Override
                    public String call (String s) {
                        try {
                            InputStream is = getActivity().getAssets().open(s);
                            Workbook rwb = Workbook.getWorkbook(is);
                            WritableWorkbook wwb = Workbook.createWorkbook(new File(
                                    MrCaiConstant.SDCARD_ROOT_PATH + s), rwb)
                                    ;// copy
                            WritableSheet ws = wwb.getSheet(0);
                            // 获得第一个工作表对象
                            int Rows = ws.getRows();
                            int Cols = ws.getColumns();
                            WritableCell wc = null;
                            // 判断单元格的类型,做出相应的转换
                            String contents = null;
                            String replaceContent = null;
                            Log.e("haitian", "rows="+Rows+"---cols="+Cols);
                            int count =0;
                            for (int i = 1; i < Rows; ++i) {
                                contents =  ws.getCell(2,i).getContents();
                                contents+=ws.getCell(6,i).getContents();
                                contents = contents.replaceAll(" ","");
                                if(oldKeyMap.containsKey(contents)){
                                    count++;
                                    replaceContent = oldKeyMap.get(contents);
                                    Log.e("haitian", "i=" + i + "-contents="
                                            + contents +
                                            "---"+replaceContent+"---count="+count);
                                    wc = ws.getWritableCell(11,i);
                                    Label label = (Label) wc;
                                    label.setString(replaceContent);
                                    if (!hasKeyMap.containsKey(contents)) {
                                        hasKeyMap.put(contents, replaceContent);
                                    }
                                }
                            }
                            wwb.write();
                            wwb.close();
                            rwb.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                }).subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
            @Override
            public void onCompleted () {
                updateOldExcel("2014_no.xls");
            }

            @Override
            public void onError (Throwable e) {

            }

            @Override
            public void onNext (String s) {
                Log.e("haitian", "s =" + s);
            }
        });
    }
    public void updateOldExcel(String filePath) {
        Observable.just(filePath)
                .subscribeOn(Schedulers.io())
                .map(new Func1<String, String>() {
                    @Override
                    public String call (String s) {
                        try {
                            InputStream is = getActivity().getAssets().open(s);
                            Workbook rwb = Workbook.getWorkbook(is);
                            WritableWorkbook wwb = Workbook.createWorkbook(new File(
                                    MrCaiConstant.SDCARD_ROOT_PATH + s), rwb)
                                    ;// copy
                            WritableSheet ws = wwb.getSheet(0);
                            // 获得第一个工作表对象
                            int Rows = ws.getRows();
                            int Cols = ws.getColumns();
                            WritableCell wc = null;
                            // 判断单元格的类型,做出相应的转换
                            String contents = null;
                            String replaceContent = null;
                            Log.e("haitian", "rows="+Rows+"---cols="+Cols);
                            int count =0;
                            for (int i = 2; i < Rows; ++i) {

                                contents =  ws.getCell(1,i).getContents();
                                contents+=ws.getCell(3,i).getContents();
                                contents = contents.replaceAll(" ","");
                                if(hasKeyMap.containsKey(contents)){
                                    count++;
                                    replaceContent = hasKeyMap.get(contents);
                                    Log.e("haitian", "i=" + i + "-contents="
                                            + contents +
                                            "---"+replaceContent+"---count="+count);
                                    wc = ws.getWritableCell(5,i);
                                    Label label = (Label) wc;
                                    label.setString("-------有------");
                                }
                            }
                            wwb.write();
                            wwb.close();
                            rwb.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                }).subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
            @Override
            public void onCompleted () {
            }

            @Override
            public void onError (Throwable e) {

            }

            @Override
            public void onNext (String s) {
                Log.e("haitian", "s =" + s);
            }
        });
    }
}
